package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

import controller.Sistema;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class AltaConjunto extends JFrame {

	private static final long serialVersionUID = 1L;
	private JLabel labelNombre;
	private JLabel labelProducto;
	private JTextField campoDescuento;
	private JLabel labelDescuento;
	private JTextField campoStock;
	private JLabel labelStock;
	private JScrollPane scrollTabla;
	private JTextField campoNombre;
	private JLabel labelTitulo;
	private JButton quitarProducto;
	private JButton botonCancelar;
	private JButton botonAceptar;
	private JComboBox<ProductoView> comboProductos;
	private JTable tablaProductos;
	private DefaultTableModel tableModel;
	private Vector<ProductoView> productos;
	private Vector<ProductoView> temporales = new Vector<ProductoView>();
	private JOptionPane MensajeConfirmacion;
	private JOptionPane MensajeError;
	
	public AltaConjunto() {
		super();
		initGUI();
		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		this.pack();
		this.setSize(468, 412);
		this.setVisible(true);
	}
	
	private class MultiColumnCellRendererProductoView extends JPanel implements ListCellRenderer<ProductoView>{
			private static final long serialVersionUID = 1L;
			private final JLabel leftLabel = new JLabel();
			private final JLabel rightLabel;
			public MultiColumnCellRendererProductoView(int rightWidth) {
			    super(new BorderLayout());
			    this.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
	
			    leftLabel.setOpaque(false);
			    leftLabel.setBorder(BorderFactory.createEmptyBorder(0,2,0,0));
	
			    final Dimension dim = new Dimension(rightWidth, 0);
			    rightLabel = new JLabel() {
					private static final long serialVersionUID = 1L;
	
				@Override public Dimension getPreferredSize() {
			        return dim;
			      }
		    };
		    rightLabel.setOpaque(false);
		    rightLabel.setBorder(BorderFactory.createEmptyBorder(0,2,0,2));
		    rightLabel.setForeground(Color.GRAY);
		    rightLabel.setHorizontalAlignment(SwingConstants.RIGHT);

		    this.add(leftLabel);
		    this.add(rightLabel, BorderLayout.EAST);
		  }
		  @Override public Component getListCellRendererComponent(JList<? extends ProductoView> list, 
				  ProductoView value, int index, boolean isSelected, boolean cellHasFocus) {
			  
		    leftLabel.setText(String.valueOf(value.getCodigo()));
		    rightLabel.setText(value.getNombreConEstacion());

		    leftLabel.setFont(list.getFont());
		    rightLabel.setFont(list.getFont());

		    if(index<0) {
		      leftLabel.setForeground(list.getForeground());
		      this.setOpaque(false);
		    }else{
		      leftLabel.setForeground(
		          isSelected?list.getSelectionForeground():list.getForeground());
		      this.setBackground(
		          isSelected?list.getSelectionBackground():list.getBackground());
		      this.setOpaque(true);
		    }
		    return this;
		  }
		  
		  @Override public Dimension getPreferredSize() {
		    Dimension d = super.getPreferredSize();
		    return new Dimension(0, d.height);
		  }		  
	}
	
	class ProductoTableModel extends DefaultTableModel{
		
		private static final long serialVersionUID = 1L;

		public boolean isCellEditable(int row, int column){
			return false;
		}		
	}
	
	private void initGUI() {
		try {
			this.setLayout(null);
			this.setPreferredSize(new java.awt.Dimension(468, 412));
			{
				labelTitulo = new JLabel();
				getContentPane().add(labelTitulo);
				labelTitulo.setText("Alta Conjuntos");
				labelTitulo.setBounds(12, 6, 198, 26);
				labelTitulo.setFont(new java.awt.Font("Segoe UI",0,16));
			}
			{
				labelNombre = new JLabel();
				this.add(labelNombre);
				labelNombre.setText("Nombre");
				labelNombre.setBounds(10, 44, 216, 23);
			}
			{
				campoNombre = new JTextField(20);
				this.add(campoNombre);
				campoNombre.setBounds(226, 44, 226, 23);
			}
			{
				labelProducto = new JLabel();
				this.add(labelProducto);
				labelProducto.setText("Producto a agregar");
				labelProducto.setBounds(10, 145, 216, 23);
			}
			{
				labelDescuento = new JLabel();
				getContentPane().add(labelDescuento);
				labelDescuento.setBounds(12, 76, 216, 23);
				labelDescuento.setText("Descuento");
			}
			{
				campoDescuento = new JTextField();
				getContentPane().add(campoDescuento);
				campoDescuento.setBounds(226, 77, 226, 23);
			}
			{
				labelStock = new JLabel();
				getContentPane().add(labelStock);
				labelStock.setBounds(12, 111, 216, 23);
				labelStock.setText("Stock");
			}
			{
				campoStock = new JTextField();
				getContentPane().add(campoStock);
				campoStock.setBounds(226, 112, 226, 23);
			}
			{
				productos = Sistema.getInstance().obtenerVistaProductos();
				comboProductos = new JComboBox<ProductoView>(productos);
				ListCellRenderer<ProductoView> renderer = new MultiColumnCellRendererProductoView(180);
				comboProductos.setRenderer(renderer);
				this.add(comboProductos);
				comboProductos.setBounds(226, 145, 226, 23);
				comboProductos.addActionListener(new ActionListener(){

					public void actionPerformed(ActionEvent e) {
						ProductoView p = (ProductoView) comboProductos.getSelectedItem();
						tableModel.addRow(new Object[] {p.getCodigo(),p.getNombre(),p.getEstacion(),p.getStock()});
						temporales.add(p);
						productos.remove(p);
					}
					
				});
			}
			{
				scrollTabla = new JScrollPane();
				getContentPane().add(scrollTabla);
				scrollTabla.setBounds(12, 180, 440, 118);
				{
					tablaProductos = new JTable();
					tableModel = new ProductoTableModel();
					tableModel.addColumn("Codigo");
					tableModel.addColumn("Nombre");
					tableModel.addColumn("Estacion");
					tableModel.addColumn("Stock");
					tablaProductos.setModel(tableModel);
					scrollTabla.setViewportView(tablaProductos);
				}
			}
			{
				quitarProducto = new JButton();
				this.add(quitarProducto);
				quitarProducto.setText("Quitar Producto");
				quitarProducto.addActionListener(new ActionListener() {
					
					public void actionPerformed(ActionEvent evt) {
						int row = tablaProductos.getSelectedRow();
						int codigo = Integer.valueOf(tablaProductos.getModel().getValueAt(row, 0).toString());
						tableModel.removeRow(row);
						for (ProductoView p: temporales){
							if (p.getCodigo() == codigo){
								comboProductos.addItem(p);
							}
						}
						
					}
				});
				quitarProducto.setBounds(329, 313, 113, 58);
			}
			{
				botonCancelar = new JButton();
				this.add(botonCancelar);
				botonCancelar.setText("Cancelar");
				botonCancelar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						close();
					}
				});
				botonCancelar.setBounds(182, 330, 93, 23);
			}
			{
				botonAceptar = new JButton();
				this.add(botonAceptar);
				botonAceptar.setText("Aceptar");
				botonAceptar.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent evt) {
						
						try {
							Vector<String> codigos = new Vector<String>();
							for (int i=0; i < tablaProductos.getRowCount();i++){
								codigos.add(tablaProductos.getValueAt(i, 0).toString());
							}
							boolean rc = Sistema.getInstance().altaConjunto(
									campoNombre.getText(), 
									Float.valueOf(campoDescuento.getText()),
									Integer.valueOf(campoStock.getText()),
									codigos
									);
							if (rc){
								JOptionPane.showMessageDialog(MensajeConfirmacion, "El conjunto se ha creado satisfactoriamente.");
								setVisible(false);
							}else{
								JOptionPane.showMessageDialog(MensajeError, "Ya existe un conjunto con ese nombre!","Error!",JOptionPane.ERROR_MESSAGE);
							}
						} catch (NumberFormatException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
				});
				botonAceptar.setBounds(24, 330, 93, 23);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void close() {
		this.dispose();
	}
	

}
